#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>

static int lock_fd = 0;
static char *lock_file_name = "test.lock";

int write_pid_to_file(void);
int set_lock_exclusive(int fd);

#define EXIT_FAILURE 1

static void olsr_create_lock_file(void) {
    
  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

  /* create file for lock */
  lock_fd = open(lock_file_name, O_RDWR | O_CREAT, mode);
  if (lock_fd == 0) {
    close(lock_fd);
    fprintf(stderr,
        "Error, cannot create OLSR lock '%s'.\n",
        lock_file_name);
    exit(EXIT_FAILURE);
  }

  /* create exclusive lock for the whole file */
  if (set_lock_exclusive(lock_fd) == -1) {
    close(lock_fd);
    fprintf(stderr,
            "Error, cannot acquire OLSR lock '%s'.\n"
            "Another instance of OLSR might be running.\n",
            lock_file_name);
  } else if (write_pid_to_file() == -1) {
    close(lock_fd);
    fprintf(stderr,
            "Error, cannot write pid to lock '%s'.\n",
            lock_file_name);
  } else {
    printf("Successfully created lock file '%s'.\n"
           "Wrote pid to lock file.\n",
           lock_file_name);
    close(lock_fd);
  }
    
  return;
}

int write_pid_to_file(void)
{
  int pid = (int)getpid();
  FILE *pid_file = fopen(lock_file_name, "w");

  if (pid_file != NULL)
    return fprintf(pid_file, "%d\n", pid);
  else
    return -1;
}

int main(int argc, char *argv[]) {
	olsr_create_lock_file();
	return 0;
}

int set_lock_exclusive(int fd)
{
  struct flock lck;

  lck.l_type = F_WRLCK;
  lck.l_whence = SEEK_SET;
  lck.l_start = 0;
  lck.l_len = 0;
  lck.l_pid = 0;

  return fcntl(fd, F_SETLKW, &lck);
}

